import json
import re
import time

import requests
from urllib.parse import quote

with open('cookie.json','r',encoding='utf-8') as f:
    headers = json.load(f)
def 获取业务信息(reciveNum):
    '''
    通过流水号获取事项的itemID 区划编码
    '''
    params = {
        "method": "queryBusinessInfo",
    }

    data = {"reciveNum":reciveNum}

    response = requests.post(
        'http://59.215.206.188/tyspzy/approval/business/error',
        params=params,

        headers=headers,
        json=data,

    ).json()
    lists= []
    lists.append([response['busiBean']['itemId'], response['busiBean']['regionCode']])
    item_code=getItemCode(lists)
    print(item_code)
    res=queryItem(item_code,response['busiBean']['regionCode'])
    return res



def getItemCode(itemid):
    params = {
        'itemid': itemid[0],
        'flag': 'consignee',
        '_': int(time.time() * 1000),
    }

    response = requests.get(
        'http://59.215.206.188/tyspzy/approval/systemsetting/approvalitem/attrshow',
        params=params,

        headers=headers,
        verify=False,
    ).text
    # 正则模式：开头 + 非贪婪匹配中间内容 + 结尾
    pattern = r'<th>事项编号：</th>.*?<b>\s*(.*?)\s*</b></td>'

    # 提取（re.DOTALL让.匹配换行符）
    result = re.findall(pattern, response, re.DOTALL)

    return result[0]


def queryItem(item_code,regionCode,itemType=None):
    data = {
        '_search': 'true',
        'nd': int(time.time() * 1000),
        'rows': '1000',
        'page': '1',
        'sidx': 'CODE',
        'sord': 'desc',
        'icode': item_code,
        'iname': '',
        'iorg': '',
        'iorgss': '',
        'regionCode': regionCode,
        'assort': '0',
        'itemType': itemType,
        'subType': '',
        'useInnerCode': '0',
        'Item': '',
        'isNewItem': '',
    }

    response = requests.post(
        'http://59.215.206.188/tyspzy/approval/systemsetting/approvalitem/query',

        headers=headers,
        data=data,
        verify=False,
    )
    lists = []
    for i in response.json()['rows']:
        if i['cell']['TYPE'] !="XN" and 'FORM' not in i['cell']:


            lists.append([i['cell']['ITEM_ID'],#0
                          i['cell']['CODE'],
                          i['cell']['AGENT_CODE'],
                          i['cell']['AGENT_NAME'],#3
                          i['cell']['REGION_CODE'],
                          i['cell']['REGION_NAME'],
                          i['cell']['NAME'],#6
                          i['cell']['TYPE'],
                          i['cell']['VERSION'],#8
                          i['cell']['AGREE_TIME'],#9
                          ])


    lists2=[]
    for i in lists:
        lists2.append(save(i))
    print(lists2)
    return lists2


def save(lists):



    params = {
        'method': 'saveExt',
    }

    data = {
	"itemId": lists[0],
	"itemCode": lists[1],
	"ishall": "0",
	"isExchange": "0",
	"fileMustUpload": "0",
	"licenseFileMustUpload": "",
	"noSubmitTime": "0",
	"isImmediate": "",
	"type": "1,2,3",
	"formId": "1089968970515087360",
	"formType": "SAAS",
	"formObjectNew": "",
	"publicAutoCode": "",
	"formName": "业务表单",
	"waringTime": "0",
	"waringTimeUnit": "day",
	"subProcessLimitTime": "",
	"subProcessLimitTimeUnit": "day",
	"subNodeId": "",
	"itemTime": lists[9],
	"itemTimeUnit": "workday",
	"orgCode": lists[2],
	"orgName": lists[3],
	"regCode": lists[4],
	"regName": lists[5],
	"isFreeTradeZone": "",
	"isSetUp": "0",
	"projectType": "00",
	"officialType": "",
	"isImportant": "0",
	"itemName": quote(quote(lists[6])),
	"itemHandleName": "",
	"itemAssort": "1",
	"itemIsPyc": "",
	"agentName": lists[3],
	"itemType": lists[7],
	"subType": "",
	"agentCode": lists[4],
	"isUniteCert": "",
	"isHiddenForm": "0",
	"isPublicity": "1",
	"isCorrectionApply": "0",
	"version": lists[8],
	"provinceItemCode": "",
	"push_val": [],
	"fileType": "",
	"smartItem": "",
	"isBuild": "0",
	"acceptanceCheck": "0",
	"nodeGroup": [],
	"preliminaryApproval": "0",
	"itemAttribute": "",
	"supervisePowerLevel": "",
	"isProvinceLicense": "0"
}
    responses = requests.post(
        'http://59.215.206.188/tyspzy/approval/systemsetting/approvalitem',
        params=params,
        headers=headers,
        json=data,
        verify=False,
    ).text
    # print(responses)
    return responses


